extends Node

@export var initstate:State
var CurrentState:State
var states:Dictionary = {}
var character:CharacterBody2D
var init_position:Vector2 = Vector2.ZERO
@onready var player_sprite: AnimatedSprite2D = $"../PlayerSprite"
@onready var playerwalk: Playerwalk = $Playerwalk
@onready var playerjump: Playerjump = $Playerjump

func _ready() -> void:
	character = get_parent() as CharacterBody2D
	for child in get_children():
		if child is State:
			states[child.name] = child
			child.transition_requested.connect(on_transition_requested)
			child.character = character
	init_position = character.global_position
			
	if initstate:
		initstate.enter()
		CurrentState = initstate
		
func _process(delta: float) -> void:
	if CurrentState:
		CurrentState.update(delta)
	if Input.is_action_just_pressed("玩家向左走"):
		InputBuffer.buffer_input("玩家向左走")
	if Input.is_action_just_pressed("玩家向右走"):
		InputBuffer.buffer_input("玩家向右走")
	if Input.is_action_just_pressed("玩家跳跃"):
		InputBuffer.buffer_input("玩家跳跃")
	if Input.is_action_just_pressed("冲刺"):
		InputBuffer.buffer_input("冲刺")

func _physics_process(delta: float) -> void:
	if CurrentState:
		CurrentState.physics_update(delta)
		
func on_transition_requested(new_state_name:String):
	if !states.has(new_state_name) or CurrentState.name == new_state_name:
		return

	if CurrentState:
		CurrentState.exit()
		CurrentState = states[new_state_name]
		CurrentState.enter()
		
func _on_main_game_event(event_type:String):
	print("状态机接受到信号")
	match event_type:
		"Playerdead":
			on_transition_requested("Playerdead")
		"PlayerSpecial":
			on_transition_requested("PlayerSpecial")
		"Playerslow":
			playerwalk.max_velocity *= 0.5
			playerjump.max_jumping_level_speed *= 0.5
		"Playerreset":
			playerwalk.max_velocity = 400.0
			playerjump.max_jumping_level_speed = 180.0
			
			
	
